<?php

namespace addons\Contract\api\modules\v1\controllers;

use Yii;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use api\controllers\OnAuthController;
use common\helpers\ResultHelper;
use common\helpers\ArrayHelper;
use addons\Contract\common\models\Contract;

/**
 * @property \yii\db\ActiveRecord|\yii\base\Model $modelClass;
 * @author 古月 <21931118@qq.com>
 */
class DefaultController extends OnAuthController
{
    public $modelClass = Contract::class;

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = ['index', 'view','type'];

    public function actionIndex()
    {
        return new ActiveDataProvider([
            'query' => $this->modelClass::find()
                ->andFilterWhere(['merchant_id' => Yii::$app->user->identity->merchant_id])
                ->andFilterWhere(['cate_id' => Yii::$app->request->get('cate_id')])
                ->orderBy('id desc')
                ->asArray(),
            'pagination' => [
                'pageSize' => $this->pageSize,
                'validatePage' => false,// 超出分页不返回data
            ],
        ]);
    }
    public function actionCreate()
    {
        $model = new $this->modelClass();
        $model->attributes = Yii::$app->request->post();
        if (!$model->save()) {
            return ResultHelper::json(422, $this->getError($model));
        }
        return $model;
    }
    public function actionType()
    {
        return ArrayHelper::arrayToArrays(\addons\Contract\common\enums\ContractEnum::getMap());
    }
    public function actionDelete($id)
    {
        return $this->findModel($id)->delete();


    }
    protected function findModel($id)
    {
        /* @var $model \yii\db\ActiveRecord */
        if (empty($id) || !($model = $this->modelClass::findOne($id))) {
            throw new NotFoundHttpException('请求的数据不存在');
        }
        return $model;
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        if (in_array($action, [])) {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}
